<?php

namespace app\sys\command;

use think\Db;
use think\console\Command;
use think\console\Input;
use think\console\Output;

// 定时任务 - 取消订单,将下单后1小时未支付的订单取消 每分钟执行
class CancelOrder extends Command
{
    protected function configure()
    {
        $this->setName('cancel_order')->setDescription('取消订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job start================');

        $this->job();

        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job end================');
    }

    private function job()
    {
        $time = time();
        $bt = $time - 3660;
        $et = $time - 3600;
        $order_list = Db::name('order')->where(['status' => 0, 'ct' => [['gte', $bt], ['lte', $et]]])->select();
        Db::name('order')->where(['status' => 0, 'ct' => [['gte', $bt], ['lte', $et]]])->update(['status' => 9, 'cancel_time' => $time]);
        // 取消订单加库存
        foreach ($order_list as $key => $value) {
            foreach ($value['product'] as $k => $v) {
                $product_info = Db::name('product')->find($v['product_id']);
                if ($product_info) {
                    $stock_index = -1;
                    foreach ($product_info['specifications'] as $kk => $value) {
                        if ($value['title'] == $v['specifications']) {
                            $stock_index = $kk;
                            break;
                        }
                    }
                    $product_number = intval($v['number']);
                    if ($stock_index != -1) {
                        Db::name('product')->where('id', $product_id)->setInc("specifications.$stock_index.stock", $product_number);
                    }
                }
            }
        }
    }
}
